import requests
from lxml import html

def search_postal_code(postal_code):
    url = f'https://www.post.japanpost.jp/cgi-zip/zipcode.php?zip={postal_code}'
    headers = {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
    }
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        tree = html.fromstring(response.content)
        try:
            _1 = tree.xpath("//div[@class='pad']/table[@class='prefList sp-b10']/tbody/tr[2]/td[@class='data'][2]/small/text()")[0]
            _2 = tree.xpath("//div[@class='pad']/table[@class='prefList sp-b10']/tbody/tr[2]/td[@class='data'][3]/small/text()")[0]
            _3 = tree.xpath("//div[@class='pad']/table[@class='prefList sp-b10']/tbody/tr[2]/td[4]/div[@class='data']/p/small/a[@class='line']/text()")[0]
            _1 = _1 + _2 + _3
            return (_1)
        except Exception as e:
            _1 = _search_postal_code(postal_code)
            return (_1)
    else:
        print(f'请求失败，状态码: {response.status_code}')
        return (None, None, None)

def _search_postal_code(postal_code):
    url = f'https://www.navitime.co.jp/freeword/?keyword={postal_code}'
    headers = {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
    }
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        tree = html.fromstring(response.content)
        try:
            # 获取第一个地址链接的文本
            _1 = tree.xpath("//div[@id='address_area']//li[@class='address_link']/a/text()")[0]
            # 去掉"丁目"及前面的数字
            if _1 and '丁目' in _1:
                # 使用正则表达式去掉数字+丁目
                import re
                _1 = re.sub(r'\d+丁目', '', _1)
            return (_1)
        except Exception as e:
            print(f'错误，navitime.co.jp: {e}')
            return (None, None, None)
    else:
        print(f'请求失败，状态码: {response.status_code}')
        return (None, None, None)

if __name__ == '__main__':
    print(search_postal_code('1530043'))
    # print(_search_postal_code('135-0051'))